import request from '../utils/request';

// 模拟的用户数据
const mockUsers = [
  {
    id: 1,
    username: 'admin',
    password: 'admin123',
    role: 'ADMIN',
    name: '管理员',
    avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=admin',
  },
  {
    id: 2,
    username: 'user',
    password: 'user123',
    role: 'USER',
    name: '普通用户',
    avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=user',
  },
];

/**
 * 登录API
 * @param {Object} credentials - 包含username和password的对象
 * @returns {Promise} - 返回登录结果的Promise
 */
export const login = async (credentials) => {
  try {
    // 这里应该是调用真实的后端API，但由于是模拟环境，我们使用模拟数据
    // const response = await request.post('/auth/login', credentials);
    
    // 模拟API延迟
    await new Promise(resolve => setTimeout(resolve, 500));
    
    // 模拟登录验证
    const user = mockUsers.find(
      u => u.username === credentials.username && u.password === credentials.password
    );
    
    if (!user) {
      throw new Error('用户名或密码错误');
    }
    
    // 模拟生成token
    const token = `mock-token-${Date.now()}-${user.id}`;
    
    return {
      token,
      userInfo: {
        id: user.id,
        username: user.username,
        role: user.role,
        name: user.name,
        avatar: user.avatar,
      },
    };
  } catch (error) {
    throw error;
  }
};

/**
 * 登出API
 * @returns {Promise} - 返回登出结果的Promise
 */
export const logout = async () => {
  try {
    // 这里应该是调用真实的后端API，但由于是模拟环境，我们只返回成功
    // const response = await request.post('/auth/logout');
    
    // 模拟API延迟
    await new Promise(resolve => setTimeout(resolve, 300));
    
    return { success: true };
  } catch (error) {
    throw error;
  }
};

/**
 * 获取当前用户信息API
 * @returns {Promise} - 返回用户信息的Promise
 */
export const getUserInfo = async () => {
  try {
    // 这里应该是调用真实的后端API，但由于是模拟环境，我们从localStorage获取
    // const response = await request.get('/auth/userInfo');
    
    // 模拟API延迟
    await new Promise(resolve => setTimeout(resolve, 300));
    
    const userInfoStr = localStorage.getItem('userInfo');
    if (!userInfoStr) {
      throw new Error('未登录');
    }
    
    return JSON.parse(userInfoStr);
  } catch (error) {
    throw error;
  }
};

const authAPI = {
  login,
  logout,
  getUserInfo,
};

export default authAPI;